package com.dlwx.parttimetalent.ui;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.dlwx.parttimetalent.R;
import com.dlwx.parttimetalent.baidu.BaiduListener;
import com.dlwx.parttimetalent.baidu.LocationService;
import com.dlwx.parttimetalent.base.BaseActivity;
import com.dlwx.parttimetalent.base.MyApplication;
import com.dlwx.parttimetalent.bean.UnReadBean;
import com.dlwx.parttimetalent.comm.Constant;
import com.dlwx.parttimetalent.comm.Http;
import com.dlwx.parttimetalent.fragment.FourFragment;
import com.dlwx.parttimetalent.fragment.OneFragment;
import com.dlwx.parttimetalent.fragment.ThreeFragment;
import com.dlwx.parttimetalent.fragment.TwoFragment;
import com.dlwx.parttimetalent.fragment.ZeroFragment;
import com.dlwx.parttimetalent.service.ExampleUtil;
import com.dlwx.parttimetalent.service.MyService;
import com.dlwx.parttimetalent.utils.DealResult;
import com.dlwx.parttimetalent.utils.OkgoUtil;
import com.dlwx.parttimetalent.utils.SPUtils;
import com.dlwx.parttimetalent.utils.ToastUtils;
import com.google.gson.reflect.TypeToken;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import q.rorbin.badgeview.Badge;
import q.rorbin.badgeview.QBadgeView;

public class MainActivity extends BaseActivity implements OneFragment.MsgNumListenner {
    @BindView(R.id.fl_count)
    FrameLayout flCount;
    @BindView(R.id.rb_0)
    RadioButton rb0;
    @BindView(R.id.rb_1)
    TextView rb1;
    @BindView(R.id.rb_2)
    RadioButton rb2;
    @BindView(R.id.rb_3)
    RadioButton rb3;
    @BindView(R.id.rb_4)
    RadioButton rb4;

    @BindView(R.id.publicIV)
    ImageView publicIV;
    private List<Fragment> fragments = new ArrayList<>();
    private Fragment lastFragment;
    private Fragment fragment,zeroFragment,oneFragment,twoFragment,threeFragment,fourFragment;
    private RxPermissions rxpermissions;
    private FragmentManager manager;
    private FragmentTransaction transaction;
    private BaiduListener mListener;
    private int userId=0;
    private QBadgeView baggeVeiw;
    private Badge bagge3;
    private Badge bagge2;
    private MyBrodcastReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        receiver=new MyBrodcastReceiver();
        registerReceiver(receiver,new IntentFilter(Constant.ACTION_HX));
        manager = getSupportFragmentManager();
//        transaction = manager.beginTransaction();
        userId=(int) SPUtils.get(this, Constant.USER_ID, 0);
//        if(userId!=0){
//            HxUtils.login(userId+"");
//        };
        fragments.add(new ZeroFragment());
        fragments.add(new OneFragment());
        fragments.add(new ThreeFragment());
        fragments.add(new FourFragment());
//        changeFragment(0);
        rb0.setChecked(true);
        startFragment(0);
        rxpermissions= new RxPermissions(this);
        requetPermission();

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        getUnReadMsg();
        int type=intent.getIntExtra("type",0);
        startFragment(type);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    private void requetPermission() {
//        rxpermissions.request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
//                .subscribe(new Consumer<Boolean>() {
//                    @Override
//                    public void accept(Boolean aBoolean) throws Exception {
//                        if(aBoolean){
//                        }
//                    }
//                });
    }

    @OnClick({R.id.rb_0, R.id.rb_1, R.id.rb_2, R.id.rb_3, R.id.rb_4})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rb_0:
                startFragment(0);
                break;
            case R.id.rb_1:
                startActivity(new Intent(this,PublishActivity.class));
                break;
            case R.id.rb_2:
                startFragment(1);
                break;
            case R.id.rb_3:
                startFragment(2);
                break;
            case R.id.rb_4:
                startFragment(3);
                break;
        }
    }

    private void changeFragment(int i) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        // 上一个不为空 隐藏上一个
        if (lastFragment != null) {
            transaction.hide(lastFragment);
        }
        fragment = fragments.get(i);
        // fragment不能重复添加 // 添加过 显示 没有添加过 就隐藏
        if(i==1){
            fragments.remove(fragment);
            fragments.add(1,new TwoFragment());
        }
        fragment = fragments.get(i);
            if (fragment.isAdded()) {
                transaction.show(fragment);
            } else {
                transaction.add(R.id.fl_count, fragment);
            }
        transaction.commit();
        lastFragment = fragment;
    }
    private void startFragment(int i) {
         transaction = manager.beginTransaction();
        // 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
        hideFragments(transaction);
        switch (i) {
            case 0:
                rb0.setChecked(true);
//                zeroFragment=null;
                if (zeroFragment != null) {
                    transaction.show(zeroFragment);
                } else {
                    zeroFragment = new ZeroFragment();
                    transaction.add(R.id.fl_count, zeroFragment, "zeroFragment");
                }
                break;
            case 1:
                rb2.setChecked(true);
                oneFragment=null;
                if (oneFragment != null) {
                    transaction.show(oneFragment);
                } else {
                    oneFragment = new OneFragment();
                    transaction.add(R.id.fl_count, oneFragment, "oneFragment");
                }
                break;
            case 2:
                threeFragment=null;
                rb3.setChecked(true);
                if (threeFragment != null) {
                    transaction.show(threeFragment);
                } else {
                    threeFragment = new ThreeFragment();
                    transaction.add(R.id.fl_count, threeFragment, "threeFragment");
                }
                break;
            case 3:
                fourFragment=null;
                rb4.setChecked(true);
                if (fourFragment != null) {
                    transaction.show(fourFragment);
                } else {
                    fourFragment = new FourFragment();
                    transaction.add(R.id.fl_count, fourFragment, "fourFragment");
                }
                break;
        }
        transaction.commitAllowingStateLoss();
    }

    /**
     * 隐藏fragment
     */
    private void hideFragments(FragmentTransaction transaction) {
        rb0.setChecked(false);
        rb2.setChecked(false);
        rb3.setChecked(false);
        rb4.setChecked(false);
        if (zeroFragment != null) {
            transaction.hide(zeroFragment);
        }
        if (oneFragment != null) {
            transaction.remove(oneFragment);
        }
        if (threeFragment != null) {
            transaction.remove(threeFragment);
        }
        if (fourFragment != null) {
            transaction.remove(fourFragment);
        }
    }

    long exitTime = 0;
    // 点击返回按钮
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
                if ((System.currentTimeMillis() - exitTime) > 2000) {
                    ToastUtils.toastForShort(MainActivity.this, "再按一次退出程序");
                    exitTime = System.currentTimeMillis();
                    return false;
                } else {
                    finish();
                }
    }
        return super.onKeyDown(keyCode, event);
    }



    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter);
    }

    @Override
    public void refreshMsgNum() {
        int gyNum=0;
        int spNum=0;
        spNum= (int) SPUtils.get(MainActivity.this,Constant.MSG_SP,0);
        gyNum= (int) SPUtils.get(MainActivity.this,Constant.MSG_GY,0);
        int totalOrderNum=gyNum+spNum;
        if(bagge2==null){
            bagge2 = new QBadgeView(MainActivity.this).bindTarget(rb2);
        }
        if(totalOrderNum>0){
            bagge2.setBadgePadding(3,true).setGravityOffset(15,0,true).setBadgeNumber(totalOrderNum);
        }else {
            bagge2.setBadgeNumber(0);
        }
        startFragment(1);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
//            Log.i("wch","接收到了广播");
            try {
                if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                    String messge = intent.getStringExtra(KEY_MESSAGE);
                    String extras = intent.getStringExtra(KEY_EXTRAS);
                    StringBuilder showMsg = new StringBuilder();
                    showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                    if (!ExampleUtil.isEmpty(extras)) {
                        showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                    }
                }
            } catch (Exception e){
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getUnReadMsg();
        LocationService locationService = ((MyApplication) getApplication()).locationService;
        locationService.stop();
        Intent i=new Intent(this, MyService.class);
        startService(i);
    }

    private void getUnReadMsg() {
        OkgoUtil.post(Http.GetUserUnread, MainActivity.this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        loadingDialog.dismiss();
                        UnReadBean parentBean = DealResult.getInstance().dealDatas(MainActivity.this
                                , response, new TypeToken<UnReadBean>() {
                                }.getType());
                        if (parentBean == null) {
                            return;
                        }
                        int code = parentBean.getCode();
                        if (code == Constant.SUCESS) {
                            UnReadBean.BodyBean bean = parentBean.getBody();
                            int orderNum=bean.getOrdernum();
                            int sysNum=bean.getSysnum();
                            int tradeNum=bean.getTradenum();
                            int gyNum=bean.getGynum();
                            int spNum=bean.getSpnum();
                            int pj=bean.getPj();
                            SPUtils.put(MainActivity.this,Constant.MSG_O,orderNum);
                            SPUtils.put(MainActivity.this,Constant.MSG_S,sysNum);
                            SPUtils.put(MainActivity.this,Constant.MSG_T,tradeNum);
                            SPUtils.put(MainActivity.this,Constant.MSG_SP,spNum);
                            SPUtils.put(MainActivity.this,Constant.MSG_GY,gyNum);
                            SPUtils.put(MainActivity.this,Constant.MSG_PJ,pj);
                            int hxNum=0;
                            List<EMConversation> conversationList = new ArrayList<>();
                            Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
                            for (Map.Entry<String, EMConversation> entry : conversations.entrySet()) {
                                conversationList.add(entry.getValue());
                                hxNum= hxNum+entry.getValue().getUnreadMsgCount();
                            }
                            int totalNum=orderNum+sysNum+tradeNum+hxNum;
                            int totalOrderNum=gyNum+spNum;
                            if(bagge3==null){
                                bagge3 = new QBadgeView(MainActivity.this).bindTarget(rb3);
                            }
                            if(totalNum>0){
                                bagge3.setBadgePadding(3,true).setGravityOffset(15,0,true).setBadgeNumber(totalNum);
                            }else{
                                bagge3.setBadgeNumber(0);
                            }
                            if(bagge2==null){
                                bagge2 = new QBadgeView(MainActivity.this).bindTarget(rb2);
                            }
                            if(totalOrderNum>0){
                                bagge2.setBadgePadding(3,true).setGravityOffset(15,0,true).setBadgeNumber(totalOrderNum);
                            }else {
                                bagge2.setBadgeNumber(0);
                            }
                        } else {
                        }
//                        ToastUtils.toastForShort(MainActivity.this, parentBean.getResult());
                    }

                    @Override
                    public void onError(Response<String> response) {
                        loadingDialog.dismiss();
                        super.onError(response);
                        ToastUtils.toastForShort(MainActivity.this, getString(R.string.bad_net));
                    }
                });
    }
    public  class MyBrodcastReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            if(TextUtils.equals(intent.getAction(),Constant.ACTION_HX)){
                getUnReadMsg();
            }
        }
    }
}
